<template>
  <div>
    <div class="first-image">
      <el-image
        :preview-src-list="imageList.map(url => url.trim())"
        :preview-teleported="true"
        :src="imageList[0].trim()"
        class="image-display"
        fit="cover"
        @click="handleImageClick"
      />
    </div>
    <el-button v-if="imageList.length > 1" plain size="small" type="primary"
               @click="viewMore = !viewMore">
      {{ viewMore ? "收起" : "查看更多照片" }}
    </el-button>
    <div v-if="viewMore" class="more-images">
      <div v-for="(url, index) in imageList.slice(1)" :key="index" class="image-preview">
        <el-image
          :initial-index="index + 1"
          :preview-src-list="imageList.map(imgUrl => imgUrl.trim())"
          :preview-teleported="true"
          :src="url.trim()"
          class="image-display"
          fit="cover"
          @click="handleImageClick"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, nextTick, ref} from 'vue'

export default defineComponent({
  name: 'ImagePreviewWithMore',
  props: {
    src: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const viewMore = ref(false);

    const handleImageClick = () => {
      // 在下一个DOM更新周期添加事件监听器
      nextTick(() => {
        // 查找并添加遮罩层点击事件
        const mask = document.querySelector('.el-image-viewer__mask');
        if (mask) {
          const closePreview = (e: Event) => {
            // 确保点击的是遮罩层而不是其他元素
            if (e.target === mask) {
              const closeBtn = document.querySelector('.el-image-viewer__close');
              if (closeBtn instanceof HTMLElement) {
                closeBtn.click();
                // 移除事件监听器
                mask.removeEventListener('click', closePreview);
              }
            }
          };
          mask.addEventListener('click', closePreview);
        }
      });
    };

    const imageList = computed(() => {
      return props.src.split(',').filter(url => url.trim() !== '');
    });

    return {
      viewMore,
      imageList,
      handleImageClick
    }
  }
});
</script>

<style scoped>
.first-image {
  display: block;
}

.image-display {
  max-height: 100px;
  border-radius: 4px;
}

.more-images {
  margin-top: 10px;
}

.image-preview {
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 10px;
}

/* 限制预览图片的最大高度 */
:global(.el-image-viewer__wrapper img) {
  max-height: 40vh !important;
  object-fit: contain;
}
</style>
